import { Table, Modal, Form, Input, Tag, Typography, Descriptions, Divider, Upload, Button, message, Select, Checkbox, Space, Spin } from '@/utils/antd-imports';
import { FileTextOutlined, HourglassOutlined, UploadOutlined, PaperClipOutlined, CheckSquareOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { invoiceApi } from '@/api/invoiceApi';











import DatePicker from 'antd/es/date-picker';




import moment from 'moment';

const { Text } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;

const InvoiceTab = ({ projectId, projectCode, settlements, onInvoice }) => {
  const [form] = Form.useForm();
  const [invoiceVisible, setInvoiceVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [fileList, setFileList] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [batchMode, setBatchMode] = useState(false);
  const [invoiceStatusFilter, setInvoiceStatusFilter] = useState('all');
  const [loading, setLoading] = useState(false);
  const [invoiceList, setInvoiceList] = useState([]);

  // 加载开票单数据
  useEffect(() => {
    if (projectId) {
      loadInvoices();
    }
  }, [projectId]);

  const loadInvoices = async () => {
    if (!projectId) return;
    
    setLoading(true);
    try {
      const response = await invoiceApi.getInvoicesByProjectId(projectId);
      if (response.code === 200) {
        setInvoiceList(response.data || []);
      } else {
        message.error(response.message || '加载开票单失败');
      }
    } catch (error) {
      console.error('加载开票单失败:', error);
      message.error('加载开票单失败');
    } finally {
      setLoading(false);
    }
  };

  // 开票状态选项
  const invoiceStatusOptions = [
    { label: '待开票', value: 'not_invoiced' },
    { label: '已开票', value: 'invoiced' }
  ];

  // 处理开票
  const handleInvoice = (record) => {
    setCurrentRecord(record);
    form.setFieldsValue({
      invoiceAmount: record.totalAmount,
      actualEndDate: record.actualEndDate ? moment(record.actualEndDate) : null,
      actualHours: record.actualHours
    });
    setInvoiceVisible(true);
  };

  // 批量开票
  const handleBatchInvoice = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请至少选择一条记录');
      return;
    }
    setInvoiceVisible(true);
  };

  // 提交开票
  const submitInvoice = async () => {
    form.validateFields().then(async (values) => {
      try {
        setLoading(true);
        
        // 准备开票数据
        const invoiceData = {
          projectId: projectId,
          invoiceAmount: values.invoiceAmount,
          invoiceDate: values.actualEndDate?.format('YYYY-MM-DD') || new Date().toISOString().split('T')[0],
          invoiceStatus: '已开票',
          invoiceType: '增值税专用发票',
          remark: values.note,
          attachmentUrls: fileList.map(file => file.url || '#').join(',')
        };

        if (batchMode) {
          // 批量开票
          const selectedSettlements = settlements.filter(item => selectedRowKeys.includes(item.id));
          for (const item of selectedSettlements) {
            await invoiceApi.createInvoice({
              ...invoiceData,
              acceptanceId: item.id,
              projectName: item.projectName,
              projectCode: item.projectCode,
              subProjectName: item.subProjectName,
              invoiceAmount: item.totalAmount || values.invoiceAmount
            });
          }
        } else {
          // 单条开票
          await invoiceApi.createInvoice({
            ...invoiceData,
            acceptanceId: currentRecord.id,
            projectName: currentRecord.projectName,
            projectCode: currentRecord.projectCode,
            subProjectName: currentRecord.subProjectName,
            invoiceAmount: values.invoiceAmount
          });
        }

        message.success(batchMode ? '批量开票成功' : '开票成功');
        
        // 刷新数据
        await loadInvoices();
        
        setInvoiceVisible(false);
        form.resetFields();
        setFileList([]);
        setSelectedRowKeys([]);
        setBatchMode(false);
      } catch (error) {
        console.error('开票失败:', error);
        message.error('开票失败');
      } finally {
        setLoading(false);
      }
    });
  };

  // 处理文件上传
  const handleUploadChange = ({ fileList }) => {
    setFileList(fileList);
  };

  // 表格行选择
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedKeys) => {
      setSelectedRowKeys(selectedKeys);
    },
    getCheckboxProps: (record) => ({
      disabled: record.invoiceStatus === 'invoiced' // 仅禁用已开票的记录
    })
  };

  // 筛选可开票的记录
  const filteredSettlements = settlements.filter(item => {
    if (invoiceStatusFilter === 'all') return true;
    return item.invoiceStatus === invoiceStatusFilter;
  });

  // 表格列定义
  const columns = [
    {
      title: '开票编号',
      dataIndex: 'invoiceNo',
      key: 'invoiceNo',
      width: 150,
      render: (text) => text || <Text type="secondary">待生成</Text>
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 120
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 150
    },
    {
      title: '子项目名称',
      dataIndex: 'subProjectName',
      key: 'subProjectName',
      width: 150
    },
    {
      title: '开始时间',
      dataIndex: 'startDate',
      key: 'startDate',
      width: 120
    },
    {
      title: '实际结束时间',
      dataIndex: 'actualEndDate',
      key: 'actualEndDate',
      width: 120,
      render: (date) => date || '-'
    },
    {
      title: '实际工时',
      dataIndex: 'actualHours',
      key: 'actualHours',
      width: 80,
      render: (hours) => hours || '-'
    },
    {
      title: '需开票金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 120,
      render: (amount) => <Text strong>¥{(amount || 0)?.toLocaleString()}</Text>
    },
    {
      title: '开票金额',
      dataIndex: 'invoiceAmount',
      key: 'invoiceAmount',
      width: 120,
      render: (amount) => <Text strong>¥{(amount || 0)?.toLocaleString() || '-'}</Text>
    },
    {
      title: '开票时间',
      dataIndex: 'invoiceTime',
      key: 'invoiceTime',
      width: 120,
      render: (date) => date || '-'
    },
    {
      title: '开票状态',
      dataIndex: 'invoiceStatus',
      key: 'invoiceStatus',
      width: 120,
      render: (status) => {
        const isInvoiced = status === 'invoiced';
        return (
          <Tag color={isInvoiced ? 'green' : 'orange'} icon={isInvoiced ? <FileTextOutlined /> : <HourglassOutlined />}>
            {invoiceStatusOptions.find(s => s.value === status)?.label || status}
          </Tag>
        );
      }
    },
    {
      title: '附件',
      key: 'attachments',
      width: 100,
      render: (_, record) => (
        record.invoiceAttachments?.length > 0 ? (
          <Button 
            type="text" 
            icon={<PaperClipOutlined />} 
            onClick={() => {
              message.info(`查看附件: ${record.invoiceAttachments.map(a => a.name).join(', ')}`);
            }}
          />
        ) : null
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_, record) => (
        record.invoiceStatus === 'not_invoiced' ? (
          <a onClick={() => handleInvoice(record)}>开票</a>
        ) : null
      )
    }
  ];

  return (
    <>
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Button 
            type={batchMode ? 'primary' : 'default'} 
            icon={<CheckSquareOutlined />}
            onClick={() => setBatchMode(!batchMode)}
          >
            {batchMode ? '取消批量' : '批量选择'}
          </Button>
          
          {batchMode && (
            <Button 
              type="primary" 
              onClick={handleBatchInvoice}
              disabled={selectedRowKeys.length === 0}
            >
              批量开票 ({selectedRowKeys.length})
            </Button>
          )}
          
          <Select
            style={{ width: 120 }}
            value={invoiceStatusFilter}
            onChange={setInvoiceStatusFilter}
          >
            <Option value="all">全部状态</Option>
            <Option value="not_invoiced">待开票</Option>
            <Option value="invoiced">已开票</Option>
          </Select>
        </Space>
      </div>

      <Spin spinning={loading}>
        <Table
          columns={columns}
          dataSource={filteredSettlements}
          rowKey="id"
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1500 }}
          bordered
          rowSelection={batchMode ? rowSelection : null}
        />
      </Spin>

      {/* 开票模态框 */}
      <Modal
        title={batchMode ? '批量开票' : '项目开票'}
        visible={invoiceVisible}
        onOk={submitInvoice}
        onCancel={() => {
          setInvoiceVisible(false);
          form.resetFields();
          setFileList([]);
        }}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            invoiceAmount: currentRecord?.totalAmount
          }}
        >
          {!batchMode && currentRecord && (
            <>
              <Descriptions bordered column={1}>
                <Descriptions.Item label="项目名称">{currentRecord.projectName}</Descriptions.Item>
                <Descriptions.Item label="子项目名称">{currentRecord.subProjectName}</Descriptions.Item>
                <Descriptions.Item label="需开票金额">
                  <Text strong>¥{currentRecord.totalAmount?.toLocaleString()}</Text>
                </Descriptions.Item>
              </Descriptions>
              <Divider />
            </>
          )}
          
          {batchMode && (
            <div style={{ marginBottom: 16 }}>
              <Text strong>已选择 {selectedRowKeys.length} 条记录</Text>
            </div>
          )}
          
          <Form.Item
            name="actualEndDate"
            label="实际结束时间"
            rules={[{ required: true, message: '请选择实际结束时间' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item
            name="actualHours"
            label="实际工时"
            rules={[{ required: true, message: '请输入实际工时' }]}
          >
            <Input type="number" />
          </Form.Item>
          
          <Form.Item
            name="invoiceAmount"
            label="开票金额"
            rules={[{ required: true, message: '请输入开票金额' }]}
          >
            <Input prefix="¥" type="number" />
          </Form.Item>
          
          <Form.Item label="开票附件">
            <Upload
              fileList={fileList}
              onChange={handleUploadChange}
              beforeUpload={() => false}
            >
              <Button icon={<UploadOutlined />}>上传附件</Button>
            </Upload>
          </Form.Item>
          
          <Form.Item
            name="note"
            label="备注"
          >
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default InvoiceTab;